package servlet.user;

import entity.Apply;
import service.ApplyService;
import service.Impl.ApplyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.time.LocalDate;



@WebServlet("/user/applyAdd")
public class ApplyAddServlet extends HttpServlet {
    private ApplyService applyService = new ApplyServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        String ageStr = req.getParameter("age");
        String telephone = req.getParameter("telephone");
        String message = req.getParameter("message");

        // 解析年龄
        int age = 0;
        try {
            age = Integer.parseInt(ageStr);
        } catch (NumberFormatException e) {
            // 处理年龄解析错误，例如设置默认年龄或返回错误响应
            age = 0; // 或者设置一个合理的默认值
            // 也可以选择重定向到错误页面或返回错误信息
            // resp.sendRedirect(req.getContextPath() + "/error");
            // return;
        }

        // 创建 Apply 对象
        Apply apply = new Apply();
        apply.setName(name);
        apply.setEmail(email);
        apply.setAge(age);
        apply.setTelephone(telephone);
        apply.setMessage(message);

        // 设置 state 为 2
        apply.setState(2);

        // 设置日期为当前日期


// 设置日期为当前日期
        LocalDate currentLocalDate = LocalDate.now();
        apply.setApplyTime(Date.valueOf(currentLocalDate));
        // 添加到服务
        applyService.add(apply);

        // 重定向到用户首页
        resp.sendRedirect(req.getContextPath() + "/user/index");
    }
}
